package com.func.domain.strategy.service.rule.chain.impl;

import com.func.domain.strategy.repository.IStrategyRepository;
import com.func.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.func.domain.strategy.service.rule.chain.factory.DefaultLogicChainFactory;
import com.func.types.common.Constants;
import com.func.types.enums.ResponseCode;
import com.func.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName BackListLogicChain
 * @Description 抽奖责任链-黑名单过滤j
 * @Author: func
 * @Date 2025/2/28 12:46
 * @Version 1.0
 */

@Slf4j
@Component("rule_blacklist")
public class BlackListLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository repository;
    @Override
    public DefaultLogicChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("责任链-黑名单 开始: userId: {} strategyId: {} ruleModel: {}", userId , strategyId, ruleModel());

        // 查询规则配置
        String ruleValue  = repository.queryStrategyRuleValue(strategyId, ruleModel());
        String[] splitRuleValue = ruleValue.split(Constants.COLON);

        if (splitRuleValue.length != 2) {
            throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }

        // 从rule_value中获取奖品Id和黑名单
        Integer awardId =  Integer.parseInt(splitRuleValue[0]);
        String blackUserList = splitRuleValue[1];

        // 抽奖黑名单判断
        String[] blackUsers = blackUserList.split(Constants.SPLIT);
        for (String blackUser : blackUsers) {
            // 当前用户是黑名单用户
            if (blackUser.equals(userId)) {
                log.info("责任链-黑名单 接管: userId: {} strategyId: {} ruleModel: {}, awardId : {}", userId , strategyId, ruleModel(), awardId);
                return DefaultLogicChainFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .logicModel(ruleModel())
                        .awardRuleValue("0.01,1") // 黑名单的默认奖励
                        .build();
            }
        }

        // 放行, 过滤其他责任链
        log.info("责任链-黑名单 放行: userId: {} strategyId: {} ruleModel: {}", userId , strategyId, ruleModel());
        return this.next().logic(userId, strategyId);
    }

    @Override
    public String ruleModel() {
        return DefaultLogicChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }

}
